package utils

import (
	"errors"
	"main/src/models"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func checkPassword(inputPassword, hashFromDB string) bool {
	if err := bcrypt.CompareHashAndPassword([]byte(hashFromDB), []byte(inputPassword)); err != nil {
		return false
	}
	return true
}

func AuthenticateUser(db *gorm.DB, user *models.User) (*models.User, error) {
	var dbUser models.User
	if err := GetUser(db, user, &dbUser); err != nil {
		return nil, errors.New("user not found")
	}

	if !checkPassword(user.Password, dbUser.Password) {
		return nil, errors.New("password invalid")
	}

	return &dbUser, nil
}
